package com.cjf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjf.comon.CustomException;
import com.cjf.dto.DishDto;
import com.cjf.dto.SetmealDto;
import com.cjf.entity.DishFlavor;
import com.cjf.entity.SetmealDish;
import com.cjf.mapper.SetmealMapper;
import com.cjf.entity.Setmeal;
import com.cjf.service.SetmealDishService;
import com.cjf.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /***
     * 新增套餐 同时需要保存套餐和菜品的关系
     * @param setmealDto
     */
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息 操作setmeal表
        this.save(setmealDto);

        //获取套餐信息集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //遍历套餐数据
         setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return setmealDishes;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关系  操作setmeal_dish表

        setmealDishService.saveBatch(setmealDishes);

    }

    /***
     * 删除套餐方法  同时需要删除套餐和菜品的关联数据
     * @param ids
     */
    public void removeWithDish(List<Long> ids) {

        //查询套餐状态 确定是否可以删除 起售状态下不可删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count>0) {
            throw new CustomException("该套餐处于售卖中，不能删除!");
        }
        //删除setmeal表的数据
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        //删除setmeal_dish表中的数据
        setmealDishService.remove(queryWrapper1);
    }

    /***
     * 根据id查询套餐和口味信息
     * @param id
     */
    public SetmealDto getByIdWithFlavor(Long id) {
        //查询套餐基本信息
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();

        BeanUtils.copyProperties(setmeal,setmealDto);

        //查询当前菜品对应的口味信息 从dish_flavor表查询
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getDishId,setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }
}
